<?php

namespace app\apiadmin\service\deposit;

use app\apiadmin\model\deposit\DepositModel;
use think\facade\Db;

class DepositService
{
    private static $instance;
    private $page_size = 10;
    private $page = 1;
    private $uid = 0;
    private function __clone()
    {}
    private function __construct()
    {}
    public static function getInstance()
    {
        if (!(self::$instance instanceof self)) {
            self::$instance = new static();
        }
        return self::$instance;
    }
    public function setUid($uid)
    {
        $this->uid = $uid;
    }
    //分页列表
    public function pageList($param)
    {
        //参数判断
        $page = $this->page;
        if (isset($param['pageNumber']) && !empty($param['pageNumber'])) {
            $page = $param['pageNumber'];
        }
        $page_size = $this->page_size;
        if (isset($param['pageSize']) && !empty($param['pageSize'])) {
            $page_size = $param['pageSize'];
        }
        //获取数据
        $where = [
            ['d.del', '=', 0],
        ];
        if (isset($param['deposit_num']) && !empty($param['deposit_num'])) {
            $where[] = ['d.deposit_num', '=', $param['deposit_num']];
        }
        if (isset($param['course_name']) && !empty($param['course_name'])) {
            $where[] = ['c.name', 'like', '%' . $param['course_name'] . '%'];
        }

        if (isset($param['state']) && in_array($param['state'], [0, 1, 2])) {
            $where[] = ['d.state', '=', $param['state']];
        }

        if (isset($param['tel']) && !empty($param['tel'])) {
            $where[] = ['d.tel', '=', $param['tel']];
        }

        if (isset($param['nick_name']) && !empty($param['nick_name'])) {
            $where[] = ['m.nick_name', '=', $param['nick_name']];
        }

        if (isset($param["create_time"]) && !empty($param["create_time"])) {
            $where[] = ["d.create_time", '>', $param["create_time"][0]];
            $where[] = ["d.create_time", '<=', $param["create_time"][1]];
        }

        if (isset($param["pay_time"]) && !empty($param["pay_time"])) {
            $where[] = ["d.pay_time", '>', $param["pay_time"][0]];
            $where[] = ["d.pay_time", '<=', $param["pay_time"][1]];
        }

        $deposit_model = new DepositModel();

        $list = $deposit_model->searchPageList($where, $page, $page_size);

        $total = $deposit_model->searchCount($where);

        $state_list = $deposit_model->stateList();

        $pay_method_list = $deposit_model->payMethodList();
        //返回数据
        $data = ['list' => $list, 'total' => $total, 'state_list' => $state_list, 'pay_method_list' => $pay_method_list];

        return $data;
    }
    public function list($param)
    {
        //获取数据
        $where = [
            ['d.del', '=', 0],
        ];
        if (isset($param['state']) && !empty($param['state'])) {
            $where[] = ['d.state', '=', $param['state']];
        }
        if (isset($param['user_id']) && !empty($param['user_id'])) {
            $where[] = ['d.user_id', '=', $param['user_id']];
        }

        $deposit_model = new DepositModel();

        $list = $deposit_model->searchList($where);

        $total = $deposit_model->searchCount($where);

        $data = ['list' => $list, 'total' => $total];

        return $data;
    }

    public function edit($param)
    {
        $result = [
            'res' => false,
            'msg' => '保存失败',
        ];
        $id = 0;
        if (isset($param['id']) && !empty($param['id'])) {
            $id = $param['id'];
        }
        if (!isset($param['siyu_course_id']) || empty($param['siyu_course_id'])) {
            $result['msg'] = "请选择一个私域课程";
            return $result;
        }
        if (!isset($param['fee']) || empty($param['fee'])) {
            $result['msg'] = "请填写定金金额";
            return $result;
        }

        $siyu_course_id = $param['siyu_course_id'];
        $fee = bcmul($param['fee'], 100, 0);
        $data = [
            'siyu_course_id' => $siyu_course_id,
            'fee' => $fee,
        ];
        $deposit_model = new DepositModel();
        if (!$id) {
            $data['deposit_num'] = $this->makeUniqueNumber();
            $data['tutor_id'] = $this->uid;
            $res = $deposit_model->add($data);
            $result['res'] = $res;
            if ($res) {
                $result['msg'] = '添加成功';
            } else {
                $result['msg'] = '添加失败';
            }
            return $result;
        }
        $info = $deposit_model->info(['id' => $id]);
        if (!$info) {
            $result['msg'] = '定金记录不存在';
            return $result;
        }
        $res = $deposit_model->edit(['id' => $id], $data);
        $result['res'] = $res;
        if ($res) {
            $result['msg'] = '修改成功';
        } else {
            $result['msg'] = '修改失败';
        }
        return $result;
    }

    public function bindUser($param)
    {
        $result = [
            'res' => false,
            'msg' => '保存失败',
        ];
        $id = 0;
        $remark = '';
        $wx_openid = '';
        $wx_unionid = '';
        if (isset($param['id']) && !empty($param['id'])) {
            $id = $param['id'];
        }
        if (isset($param['remark']) && !empty($param['remark'])) {
            $remark = $param['remark'];
        }
        if (isset($param['wx_openid']) && !empty($param['wx_openid'])) {
            $wx_openid = $param['wx_openid'];
        }
        if (isset($param['wx_unionid']) && !empty($param['wx_unionid'])) {
            $wx_unionid = $param['wx_unionid'];
        }
        if (!isset($param['user_id']) || empty($param['user_id'])) {
            $result['msg'] = "缺少必要参数用户信息";
            return $result;
        }
        // if(!isset($param['actual_payment_fee']) || empty($param['actual_payment_fee'])){
        //     $result['msg']="缺少付款金额";
        //     return $result;
        // }
        if (!isset($param['pay_method']) || !in_array($param['pay_method'], [1, 2])) {
            $result['msg'] = "付款方式错误";
            return $result;
        }
        if (!isset($param['tel']) || empty($param['tel'])) {
            $result['msg'] = "缺少必要参数手机号";
            return $result;
        }

        $user_id = $param['user_id'];
        // $actual_payment_fee = bcmul($param['actual_payment_fee'],100,0);
        $tel = $param['tel'];
        $pay_method = $param['pay_method'];
        $data = [
            'remark' => $remark,
            'user_id' => $user_id,
            'wx_openid' => $wx_openid,
            'wx_unionid' => $wx_unionid,
            'pay_method' => $pay_method,
            // 'actual_payment_fee'=>$actual_payment_fee,
            'tel' => $tel,
        ];
        $deposit_model = new DepositModel();

        $info = $deposit_model->info(['id' => $id]);
        if (!$info) {
            $result['msg'] = '定金记录不存在';
            return $result;
        }
        if ($info['state'] > 0 && $info['pay_method'] > 0) {
            $data['pay_method'] = $info['pay_method'];
        }
        $res = $deposit_model->edit(['id' => $id], $data);
        if ($res) {
            $info = $deposit_model->info(['id' => $id]);
            $result['res'] = $info;
            $result['msg'] = '修改成功';
        } else {
            $result['res'] = $res;
            $result['msg'] = '修改失败';
        }
        return $result;
    }

    public function tuikuan($param)
    {
        $result = [
            'res' => false,
            'msg' => '退款失败',
        ];
        if (!isset($param['id']) || empty($param['id'])) {
            $result['msg'] = "缺少必要参数定金id";
            return $result;
        }
        $id = $param['id'];
        $info = $this->info(['id' => $id]);
        if (!$info) {
            $result['msg'] = "定金信息不存在";
            return $result;
        }
        if ($info['state'] != 1) {
            $result['msg'] = "定金未支付不能退款";
            return $result;
        }
        switch ($info['pay_method']) {
            case 1:
                if (strtotime($info['pay_time']) > strtotime('2024-09-01 18:30:00')) { //2024年8月23日23:30:16后走服务商退款，之前走直连退款
                    $res = \app\apiadmin\controller\live\UnionAppFuWuShang::tuikuan($info['deposit_num'], "T" . $info['deposit_num'], $info['fee'], $info['actual_payment_fee'], $info['accountid']);
                } else {
                    $res = \app\apiadmin\controller\live\UnionApp::tuikuan($info['deposit_num'], "T" . $info['deposit_num'], $info['fee'], $info['actual_payment_fee']);
                }
                //$res = \app\apiadmin\controller\live\UnionApp::tuikuan($info['deposit_num'],"T".$info['deposit_num'] , $info['actual_payment_fee'], $info['actual_payment_fee']);
                $d['remark'] = date('Y-m-d H:i:s') . '---定金---微信支付---退款回调----info---' . json_encode($info) . '------res-----' . json_encode($res);
                DB::table('xh_siyu_user_remark')->save($d);
                if ($res['code'] != 200) {
                    $result['msg'] = "微信退款失败";
                    return $result;
                }
                //微信退款
                break;
            case 2:
                if (strtotime($info['pay_time']) > strtotime('2024-09-01 18:30:00')) { //2024年8月23日23:30:16后走服务商退款，之前走直连退款
                    $res = \app\apiadmin\controller\user\User::alipay_refund2($info['trade_no'], $info['actual_payment_fee'], $info['deposit_num'], 'T' . $info['deposit_num'], -1);
                } else {
                    $res = \app\apiadmin\controller\user\User::alipay_refund($info['trade_no'], $info['actual_payment_fee'], $info['deposit_num'], 'T' . $info['deposit_num'], -1);
                }
                // $res = \app\apiadmin\controller\user\User::alipay_refund($info['trade_no'], $info['actual_payment_fee'], $info['deposit_num'], 'T'.$info['deposit_num'], -1 );
                $d['remark'] = date('Y-m-d H:i:s') . '---定金---支付宝支付---退款回调----info---' . json_encode($info) . '------res-----' . json_encode($res);
                DB::table('xh_siyu_user_remark')->save($d);
                if ($res['code'] != 0) {
                    $result['msg'] = "支付宝退款失败";
                    return $result;
                }
                //支付宝退款
                break;
            default:
                break;
        }
        $deposit_model = new DepositModel();
        $deposit_model->edit(['id' => $id], ['state' => 2, 'refund_time' => date('Y-m-d H:i:s', time())]);
        $result['res'] = true;
        $result['msg'] = '退款成功';
        return $result;
    }
    public function info($param)
    {
        $id = 0;
        if (isset($param['id']) && !empty($param['id'])) {
            $id = $param['id'];
        }
        $deposit_model = new DepositModel();
        $result = $deposit_model->info(['id' => $id]);
        if (!$result) {
            return [];
        }
        return $result;
    }

    public function makeUniqueNumber()
    {
        $number = 'SYDJ' . rand(1000, 9999) . date('YmdHis', time());
        return $number;
    }
}
